﻿using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using System.Net.Sockets;
using System.Configuration;
using System.Text.Json.Serialization;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Web;
using System.Windows.Forms;
using System.Drawing;
using System.Web.UI.WebControls;
using System.IO.Pipes;
using static System.Windows.Forms.LinkLabel;
using static System.Net.Mime.MediaTypeNames;

namespace OCR
{
    public class BaiduOCR
    {
        static GetBaiduApi BaiduApi = new GetBaiduApi();
        static Translate translate;static Language language;
        static List<Language> Languages = new List<Language>();
        static List<ImgWords> Words = new List<ImgWords>();
        static List<Translate> TranslateWords = new List<Translate>();
        Form form = new Form();
        PictureBox pictureBox1 = new PictureBox();
        RichTextBox richTextBox1 = new RichTextBox();
        RichTextBox richTextBox2 = new RichTextBox();
        ContextMenuStrip contextMenu = new ContextMenuStrip();
        ToolStripMenuItem ToolsMenuItem = new ToolStripMenuItem();
        public void GetImgCharacters(string ImgPath,PictureBox pictureBox1)
        {
            var obj = JsonConvert.DeserializeObject<JObject>(BaiduApi.general(ImgPath));
            if (obj != null)
            {
                int count = (int)obj["words_result_num"];
                //往WordsLocation中添加数据
                Words.Clear();//先清空下List集合在填充
                for (int i = 0; i < count; i++)
                {
                    ImgWords lo = new ImgWords();
                    lo.words = obj["words_result"][i]["words"].ToString();
                    lo.log_id = obj["log_id"].ToString();
                    lo.words_result_num = count.ToString();
                    lo.top = obj["words_result"][i]["location"]["top"].ToString();
                    lo.left = obj["words_result"][i]["location"]["left"].ToString();
                    lo.width = obj["words_result"][i]["location"]["width"].ToString();
                    lo.height = obj["words_result"][i]["location"]["height"].ToString();
                    Words.Add(lo);
                }

                //画矩形
                Bitmap bt = new Bitmap(pictureBox1.Image);
                Graphics gg = Graphics.FromImage(bt);
                //在图片上标记出文字位置
                foreach (var item in Words)
                {
                    gg.DrawRectangle(new Pen(Brushes.Red), float.Parse(item.left), float.Parse(item.top), float.Parse(item.width), float.Parse(item.height));
                }
                Clipboard.SetImage(bt);
                gg.Dispose();
                CutSet();
                Form1();
            }
            else
            {
                MessageBox.Show("参数错误，请检查AppKey和SecretKey");
            }
        }
        public void CutSet()
        {
            pictureBox1.Dock = DockStyle.Bottom;
            pictureBox1.Height=350;
            richTextBox1.Dock = DockStyle.Left;
            richTextBox2.Dock = DockStyle.Right;
            richTextBox1.Height = 260;
            richTextBox1.Width = 289;
            richTextBox2.Width = 285;
            richTextBox2.Width = richTextBox1.Width;
            richTextBox2.Height = richTextBox1.Height;
            richTextBox1.ContextMenuStrip = contextMenu;
            richTextBox1.WordWrap = true;
            pictureBox1.Image = Clipboard.GetImage();
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
        }
        public void Form1()
        {
            form.Controls.Add(richTextBox1);
            form.Controls.Add(richTextBox2);
            form.Controls.Add(pictureBox1);
            form.Text = "OCR";
            form.MaximizeBox = false;
            form.FormBorderStyle= FormBorderStyle.Fixed3D;
            form.Width =600; form.Height =600;
            ToolsMenuItem.Text = "翻译";
            string json = System.Windows.Forms.Application.StartupPath + "\\TranslationLanguage.json";
            using (StreamReader sr=new StreamReader(json,Encoding.Default))
            {
                string ReadJson = sr.ReadToEnd();
                var Language = JsonConvert.DeserializeObject<JObject>(ReadJson);
                for (int i = 0; i < Language["languages"].Count(); i++)
                {
                    language = new Language();
                    language.Lan= Language["languages"][i]["中文"].ToString();
                    language.Abbreviation = Language["languages"][i]["简写"].ToString();
                    Languages.Add(language);
                    ToolsMenuItem.DropDown.Items.Add(Language["languages"][i]["简写"].ToString(), null, ToolsMenuItem_Click);
                    ToolsMenuItem.DropDownItems[i].Text = Language["languages"][i]["中文"].ToString();
                }
            }
            contextMenu.Items.AddRange(new ToolStripMenuItem[] { ToolsMenuItem });
            //从Words中取出文字追加给richTextBox
            richTextBox1.Text = string.Empty;
            foreach (var item in Words)
            {
                richTextBox1.AppendText(item.words+"\n");
                //richTextBox.AppendText(item.words);
            }  
            form.ShowDialog();
        }
        private void ToolsMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
            foreach (var item in Languages)
            {
                if (item.Lan == clickedItem.Text)
                {
                    GetTrans(item.Abbreviation, richTextBox1.Text);
                    return;
                }
            }
        }
        public void GetTrans(string Len,string Text)
        {
            if (BaiduApi.TranslateClientId!="" && BaiduApi.TranslateClientSecret != "")
            {
                if (BaiduApi.textTrans(Len, Text) != "null")
                {
                    translate = new Translate();
                    var obj = JsonConvert.DeserializeObject<JObject>(BaiduApi.textTrans(Len, Text));
                    int count = (int)obj["result"]["trans_result"].Count();
                    TranslateWords.Clear();
                    for (int i = 0; i < count; i++)
                    {
                        translate = new Translate();
                        translate.log_id = obj["log_id"].ToString();
                        translate.from = obj["result"]["from"].ToString();
                        translate.to = obj["result"]["to"].ToString();
                        translate.src = obj["result"]["trans_result"][i]["src"].ToString();
                        translate.dst = obj["result"]["trans_result"][i]["dst"].ToString();
                        TranslateWords.Add(translate);
                    }
                    richTextBox1.Text = Text;
                    richTextBox2.Text = string.Empty;
                    foreach (var item in TranslateWords)
                    {
                        richTextBox2.AppendText(item.dst + "\n");
                    }
                }
            }
            else
            {
                MessageBox.Show("请在设置里添加'TranslateClientId'和'TranslateClientSecret'");
            } 
        }
        public void GetCutImgCharacters(System.Drawing.Image ImgPath)
        {
            if (BaiduApi.OCRclientId!="" && BaiduApi.OCRclientSecret!="")
            {
                if (ImgPath != null)
                {
                    if (BaiduApi.Gen(ImgPath) != "null")
                    {
                        var obj = JsonConvert.DeserializeObject<JObject>(BaiduApi.Gen(ImgPath));
                        int count = (int)obj["words_result_num"];
                        //往WordsLocation中添加数据
                        Words.Clear();//先清空下List集合在填充
                        for (int i = 0; i < count; i++)
                        {
                            ImgWords lo = new ImgWords();
                            lo.words = obj["words_result"][i]["words"].ToString();
                            lo.log_id = obj["log_id"].ToString();
                            lo.words_result_num = count.ToString();
                            lo.top = obj["words_result"][i]["location"]["top"].ToString();
                            lo.left = obj["words_result"][i]["location"]["left"].ToString();
                            lo.width = obj["words_result"][i]["location"]["width"].ToString();
                            lo.height = obj["words_result"][i]["location"]["height"].ToString();
                            Words.Add(lo);
                        }
                        //画矩形
                        Bitmap bt = new Bitmap(ImgPath);
                        Graphics gg = Graphics.FromImage(bt);
                        //在图片上标记出文字位置
                        foreach (var item in Words)
                        {
                            gg.DrawRectangle(new Pen(Brushes.Red), float.Parse(item.left), float.Parse(item.top), float.Parse(item.width), float.Parse(item.height));
                        }
                        Clipboard.SetImage(bt);
                        gg.Dispose();
                        CutSet();
                        Form1();
                    }
                }
            }
            else
            {
                MessageBox.Show("请在设置里添加'OCRclientId'和'OCRclientSecret'");
            }
        }
    }
}
